package cn.itcast.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author yangjy
 * @version 1.0
 * @description:
 * 需求：定义全局过滤器，拦截请求，判断请求的参数是否满足下面条件：
 * - 参数中是否有 authorization，
 * - authorization参数值是否为admin
 * 如果同时满足则放行，否则拦截
 * @date 2022/9/7 10:17
 */
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter{


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求参数
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
        //2.获取authorization参数
        String authorization = params.getFirst("authorization");
        //3.校验
        if("admin".equals(authorization)){
            //放行
            return chain.filter(exchange);
        }
        //4.拦截
        //4.1 禁止访问，设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        //4.2 结束处理
        return exchange.getResponse().setComplete();
    }
}
